//
//  HUD.swift
//  BWPanelKit
//
//  Created by zhuxuhong on 2022/3/7.
//

import UIKit
import BWToolKit
import BWPopupView

public enum HUD {
    case toast(_ value: Toast)
    case square(_ value: Square)
    case snackbar(_ value: Snack)
    case popup(_ value: Popup)
    
    public struct Configure {
        public var appearance: Appearance = .defaultDark
    }
    public static var shared = Configure()
    static var showings: [UIViewController] = []
    
    @discardableResult
    public static func show(_ hud: HUD, completion: BlockVoid? = nil) -> UIViewController {
        var vc: UIViewController!
        switch hud {
        case .toast(let value):
            vc = HUDToastVC(hud: value, completion: completionHandler(completion))
        case .square(let value):
            vc = HUDSquareVC(hud: value, completion: completionHandler(completion))
        case .snackbar(let value):
            vc = HUDSnackbarVC(hud: value, completion: completionHandler(completion))
        case .popup(let value):
            vc = showPopup(value, completion: completionHandler(completion))
        }
        showings.append(vc)
        if let hudVC = vc as? HUDVC {
            hudVC.show()
        }
        return vc
    }
    
    static func completionHandler(_ callback: BlockVoid? = nil) -> BlockVoid? {
        return {
            let dismissed = showings.filter{ $0.parent == nil }
            showings.removeAll(dismissed)
            callback?()
        }
    }
    
    public static func dismiss(first type: HUDType){
        guard let vc = showings.first(where: { type.isMatched(of: $0) }) else {
            return
        }
        dismiss(vc, completion: nil)
    }
    public static func dismiss(last type: HUDType){
        guard let vc = showings.last(where: { type.isMatched(of: $0) }) else {
            return
        }
        dismiss(vc, completion: nil)
    }
    public static func dismiss(all type: HUDType){
        let alls = showings.filter{ type.isMatched(of: $0) }
        for vc in alls {
            dismiss(vc, completion: nil)
        }
    }
    
    public static func dismissAll() {
        showings.forEach{ dismiss($0) }
    }
    
    public static func dismiss(_ completion: BlockVoid? = nil) {
        dismiss(showings.first, completion: completion)
    }
    
    public static func dismiss(_ hud: UIViewController?, completion: BlockVoid? = nil){
        if let hudVC = hud as? HUDVC {
            hudVC.dismiss(completion: completion)
        }
        else if let popupVC = hud as? BWPopupController {
            popupVC.dismiss(completion: completion)
        }
    }
}


